<template>
  <a-layout style="height: 100vh;">
    <a-layout-content>
      <a-row type="flex" justify="center" style="margin-top: 20vh;">
        <a-col :sm="{span: loginType === CONSTANT.LOGIN_TYPE.REGISTER ? 8 : 6}" :xs="{span: 20}">
          <a-card v-if="loginType === CONSTANT.LOGIN_TYPE.ACCOUNT" title="账号密码登录" :bordered="true">
            <a-form :label-col="{span: 8}" :wrapper-col="{ span: 16 }">
              <a-form-item label="账号 / 邮箱">
                <a-input v-model="userInfo.account"></a-input>
              </a-form-item>
              <a-form-item label="密码">
                <a-input-password v-model="userInfo.password" @keydown.enter="handleLogin"></a-input-password>
              </a-form-item>
              <a-col :style="{textAlign: 'right'}">
                <a-button v-if="false" @click="checkLogin">检查登录状态</a-button>
                <a-button style="margin-left: 16px" @click="loginType = 2">注册</a-button>
                <a-button style="margin-left: 16px" @click="loginType = 1">二维码登录</a-button>
                <a-button style="margin-left: 16px" type="primary" @click="handleLogin" :loading="isLoginHanding">登录</a-button>
              </a-col>
            </a-form>
          </a-card>
          <a-card v-else-if="loginType === CONSTANT.LOGIN_TYPE.QRCODE" title="二维码登录" :bordered="true">
            <a-form :label-col="{span: 4}" :wrapper-col="{ span: 20 }">
              <span>请使用移动端H5页面登录操作</span>
              <span>由于移动端浏览器限制，请先拍照二维码，再在移动端进行上传</span>
              <div v-if="!isScanned" class="qrcode-wrapper" style="position: relative; width: 100%; text-align: center">
                <img v-if="qrInfo !== null" 
                     style="width: 256px; height: 256px; margin-top: 8px;" 
                     :src="remainMilliseconds !== null && remainMilliseconds > 0 ? qrInfo['qr'] : qrInfo['qrTimeout']" 
                />
                <div v-else
                     style="width: 256px; 
                       height: 256px; 
                       margin-top: 8px;
                       background-color: rgba(0, 0, 0, .01); 
                       text-align: center;
                       display: inline-flex;
                       justify-content: center;
                       align-items: center;"
                >
                  <a-spin />
                </div>
                <div v-show="isShowRefresh" 
                     style="position: absolute; 
                            left: 0;
                            right: 0;
                            top: 8px;
                            display: flex;
                            margin-left: auto;
                            margin-right: auto;
                            justify-content: center; 
                            align-items: center; 
                            width: 256px; 
                            z-index: 1;
                            height: 256px; 
                            background-color: rgba(0, 0, 0, .1);"
                >
                  <a-button shape="circle" icon="redo" size="large" @click="getQrLoginInfo" />
                </div>
              </div>
              <div v-else class="qrcode-wrapper" style="position: relative; width: 100%; text-align: center; padding-top: 32px;">
                <a-avatar v-if="scanInfo.avatar" :src="scanInfo.avatar" :size="64" />
                <a-avatar v-else icon="user" :size="64" />
                <p style="margin-top: 24px; font-size: 18px;">{{scanInfo.nickname}}</p>
                <p style="margin-top: 24px; font-size: 18px;">请在{{scanInfo.device}}设备上确认登录</p>
              </div>
              <a-col :style="{textAlign: 'right', marginTop: '18px'}">
                <a-button @click="loginType = 0">账号登录</a-button>
              </a-col>
            </a-form>
          </a-card>
          <a-card v-if="loginType === CONSTANT.LOGIN_TYPE.REGISTER" title="注册" :bordered="true" >
            <a-form :label-col="{span: 6}" :wrapper-col="{ span: 18 }">
              <a-form-item label="电子邮箱" :required="true">
                <a-input v-model="regInfo.email"></a-input>
              </a-form-item>
              <a-form-item label="账号" :required="true">
                <a-input v-model="regInfo.username"></a-input>
              </a-form-item>
              <a-form-item label="密码" :required="true">
                <a-input-password v-model="regInfo.password"></a-input-password>
              </a-form-item>
              <a-form-item label="用户名" :required="true">
                <a-input v-model="regInfo.nickname"/>
              </a-form-item>
              <a-form-item label="生日">
                <a-date-picker v-model="regInfo.birthday"/>
              </a-form-item>
              <a-col :style="{textAlign: 'right'}">
                <a-button @click="loginType = 0">登录</a-button>
                <a-button style="margin-left: 16px" type="primary" @click="handleRegister">注册</a-button>
              </a-col>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<script>
import CONSTANT from '@/utils/constant'
import moment from 'moment'

export default {
  name: 'index',
  data: _ => ({
    userInfo: {
      account: '',
      password: '',
    },
    regInfo: {
      username: '',
      password: '',
      email: '',
      birthday: new moment(),
      nickname: '',
    },
    loginType: 0,
    qrInfo: null,
    isShowRefresh: true,
    remainMilliseconds: null,
    timeCountDownHandler: null,
    isScanned: false,
    scanInfo: null,
    isLoginHanding: false,
    CONSTANT,
  }), 
  methods: {
    async handleRegister () {
      let regReqParam = {...this.regInfo}
      regReqParam['birthday'] = regReqParam['birthday'].toDate()
      try {
        let {data} = await this.$http.post('/register', regReqParam)
        this.$message.success(data.msg + "，跳转到登录页面")
        this.loginType = CONSTANT.LOGIN_TYPE.ACCOUNT
      } catch ({data}) {
        this.$message.error(data.msg)
      }
    },
    async checkLogin () {
      let { data } = await this.$http.get('/login')
      this.$message.info(data.msg)
    },
    async handleLogin () {
      try {
        this.isLoginHanding = true
        let { data } = await this.$http.post('/login', { ...this.userInfo })
        this.isLoginHanding = false
        this.$message.success(data.msg)
        if (data.code === CONSTANT.RESP.SUCCESS) {
          let loginInfo = data.data
          localStorage.setItem("token", JSON.stringify(loginInfo['tokenInfo']))
          localStorage.setItem('userInfo', JSON.stringify(loginInfo['userInfo']))
          this.$router.push('/').then(_ => {})
        }
      } catch ({data}) {
        this.isLoginHanding = false
        switch (data.code) {
          case CONSTANT.RESP.ALREADY_LOGIN:
            this.$router.push('/profile').then(r => {})
            this.$message.info(data.msg)
            break
          default:
            this.$message.error(data.msg)
        }
      }
    },
    async getQrLoginInfo () {
      try {
        this.qrInfo = null
        this.isShowRefresh = false
        let {data} = await this.$http.get("/qrcode/login")
        this.qrInfo = data.data
        this.remainMilliseconds = this.qrInfo['timeout']
        if (this.timeCountDownHandler) clearInterval(this.timeCountDownHandler)
        this.timeCountDownHandler = setInterval(async _ => {
          let {data} = await this.$http.get(this.qrInfo['checkUrl'])
          if (!this.isScanned) {
            if (data.data['scanned']) {
              this.isScanned = true
              this.scanInfo = {
                nickname: data.data['nickname'],
                avatar: data.data['avatar'],
                device: data.data['device'],
              }
            }
          } else {
            if (data.data['loginPermitted']) {
              clearInterval(this.timeCountDownHandler)
              this.$message.success('客户端已允许登录，正在登录中...')
              let {data: respData} = await this.$http.post(this.qrInfo['loginUrl'])
              if (respData.code === CONSTANT.RESP.SUCCESS) {
                let loginInfo = data.data
                localStorage.setItem("token", JSON.stringify(loginInfo['tokenInfo']))
                localStorage.setItem('userInfo', JSON.stringify(loginInfo['userInfo']))
                this.$router.push('/').then(_ => {})
              }
              this.$message.success(respData.msg)
            }
          }
          this.remainMilliseconds -= 1000
          if (this.remainMilliseconds <= 0) {
            this.isShowRefresh = true
            clearInterval(this.timeCountDownHandler)
          }
        }, 1000)
      } catch ({data}) {
        this.isShowRefresh = true
        this.$message.error(data.msg)
      }
    },
    clearInterval () {
      if (this.timeCountDownHandler) {
        clearInterval(this.timeCountDownHandler)
      }
    },
  },
  watch: {
    loginType (newVal) {
      switch (newVal) {
        case CONSTANT.LOGIN_TYPE.ACCOUNT:
          if (this.timeCountDownHandler) {
            clearInterval(this.timeCountDownHandler)
          }
          break
        case CONSTANT.LOGIN_TYPE.QRCODE:
          this.getQrLoginInfo()
          break
        case CONSTANT.LOGIN_TYPE.REGISTER:
          if (this.timeCountDownHandler) {
            clearInterval(this.timeCountDownHandler)
          }
          break
        default:
          break
      }
    }
  },
  beforeDestroy() {
    this.clearInterval();
  }
}
</script>

<style>

</style>